package com.briup.ptt.service.Impl;

import com.briup.ptt.bean.Account;
import com.briup.ptt.exception.CustomException;
import com.briup.ptt.mapper.ext.AccountExtMapper;
import com.briup.ptt.service.AccountService;
import com.briup.ptt.util.BriupAssert;
import com.briup.ptt.util.JWTUtil;
import com.briup.ptt.util.EmailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailSender;
import org.springframework.stereotype.Service;

import java.util.Map;

import static com.briup.ptt.constant.BriupConstant.ACCOUNT_STATES_DISABLED;
import static com.briup.ptt.constant.BriupConstant.ACCOUNT_STATES_USABLE;

/**
 * @author 杰瑞
 * @date 2025/8/15
 */
@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountExtMapper accountExtMapper;

    @Autowired
    private EmailUtil emailUtil;

    @Override
    public String loginEmail(String email, String emailCode) {

        Account account = accountExtMapper.selectByEmail(email);
        //判断邮箱验证码是否正确
        String cacheCode = emailUtil.getCacheCode(email);
        BriupAssert.isTrue(cacheCode.equals(emailCode), "邮箱验证码错误");

        BriupAssert.isTrue(account.getStatus() == ACCOUNT_STATES_USABLE, "用户被禁用");

        Map<String, Object> info = Map.of("realName", account.getRealname(),
                "email", account.getEmail());
        String userId = account.getAccountId();
        String token = JWTUtil.createToken(userId, info);

        return token;
    }


    @Override
    public String sendEmail(String email) {

        Account account = accountExtMapper.selectByEmail(email);
        if( account.getEmail() == null){
            throw new CustomException("该邮箱未注册,请先注册");
        }

        //一分钟之内只能请求一次
        String code = emailUtil.getCacheCode(email);
        if (code != null) {
            throw new CustomException("请勿频繁请求,1分钟之后再试");
        }

        //随机生成6位验证码
        String emailCode = emailUtil.generatorCode(email);
        //发送邮件
        return  emailUtil.sendEmail(email,emailCode);
    }

    @Override
    public String login(String username, String password) {

        Account account = accountExtMapper.selectByUserName(username);


        BriupAssert.notNull(account, "用户不存在");

        BriupAssert.isTrue(account.getPassword().equals(password), "密码错误");

        BriupAssert.isTrue(account.getStatus() == ACCOUNT_STATES_USABLE, "用户被禁用");

        String userId = account.getAccountId();
        Map<String, Object> info = Map.of("realName", account.getRealname(),
                "email", account.getEmail());

        return JWTUtil.createToken(userId, info);
    }

    @Override
    public Account findLoginUser(String token) {
        String userId = JWTUtil.getUserId(token);

        return accountExtMapper.selectByUserName(userId);


    }
}
